package com.shengl.app.model.RowMapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.apache.commons.collections.map.ListOrderedMap;

import com.shengl.app.util.JdbcUtils;
import com.shengl.app.util.RowMapper;

public class ColumnMapRowMapper implements RowMapper {

	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		// TODO Auto-generated method stub
		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		Map mapOfColValues = createColumnMap(columnCount);
		for (int i = 1; i <= columnCount; i++) {
			String key = getColumnKey(rsmd, i);
			Object obj = getColumnValue(rs, i);
			mapOfColValues.put(key, obj);
		}
		return mapOfColValues;
	}

	private Object getColumnValue(ResultSet rs, int index) throws SQLException {
		// TODO Auto-generated method stub
		return JdbcUtils.getResultSetValue(rs, index);
	}

	private String getColumnKey(ResultSetMetaData rsmd, int i) throws SQLException {
		// TODO Auto-generated method stub
		return JdbcUtils.lookupColumnName(rsmd, i);
	}

	private Map createColumnMap(int columnCount) {
		// TODO Auto-generated method stub
		return ListOrderedMap.decorate(new CaseInsensitiveMap(columnCount == 0 ? 1 : columnCount));
	}

}
